// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package main

import (
	"apiote.xyz/p/szczanieckiej/config"
	"apiote.xyz/p/szczanieckiej/server"
	"apiote.xyz/p/szczanieckiej/traffic"

	"context"
	"embed"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
)

//go:embed translations
var feedTranslations embed.FS

func main() {
	if len(os.Args) == 1 {
		fmt.Println("szczanieckiej [-c <config>] <command> ")
		os.Exit(1)
	}
	configFilePath := "/etc/szczanieckiej.toml"
	command := os.Args[1]
	if os.Args[1] == "-c" {
		configFilePath = os.Args[2]
		command = os.Args[3]
	}
	cfg, err := config.Read(configFilePath)
	if err != nil {
		log.Printf("Error while reading config file, %v\n", err)
		os.Exit(1)
	}

	t := traffic.Traffic{}
	traffic.EnableFeeds(cfg, &t)

	switch command {
	case "convert":
		err := traffic.Prepare(cfg, t, -1, feedTranslations)
		if err != nil {
			log.Println(err)
			os.Exit(1)
		}
	case "serve":
		fmt.Println("The wheels on the bus go round and round")
		c := make(chan os.Signal, 1)
		d := make(chan bool)
		i := make(chan bool, 1)
		signal.Notify(c, os.Interrupt, syscall.SIGUSR1)
		go traffic.Initialise(c, d, i, cfg, &t)
		c <- syscall.SIGUSR1
		srv := server.RoutePreinit(cfg)
		<-i
		if err := srv.Shutdown(context.Background()); err != nil {
			panic(err)
		}
		srv = server.Route(cfg, &t)
		<-d
		if err := srv.Shutdown(context.Background()); err != nil {
			panic(err)
		}
		fmt.Println("\nNothing Arrived")
	}
}
